﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace DeepHash.Document
{
    /// <summary>
    /// A root document object that represents and contains
    /// the result of file verification.
    /// </summary>
    [System.Xml.Serialization.XmlRoot("hashDocument")]
    public class VerificationDocument : FolderVerificationRecord
    {
        private string _hashAlgorithem = "MD5";
        [System.Xml.Serialization.XmlAttribute("hashAlgorithem")]
        public string HashAlgorithem 
        {
            get { return _hashAlgorithem; }
            internal set { _hashAlgorithem = value; }
        }

        /// <summary>
        /// Saves the file in the specified format 
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool SaveFile(string filename, Format.IDocumentFormatter formatter)
        {
            // Delete the file if it already exists
            if (File.Exists( filename)) 
            {
                File.Delete (filename);
            }
            bool ret = false;
            FileStream fs = null;
            try
            {
                // Create the file.
                fs = new FileStream(filename, FileMode.CreateNew);
                // Make the formatter write to the file
                formatter.SaveDocument(fs, this);
                ret = true;
            }
            finally
            {
                // Make sure we close the stream
                fs.Close();
            }
            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="formatter"></param>
        /// <returns></returns>
        public static VerificationDocument LoadFromFile(string filename, Format.IDocumentFormatter formatter)
        {
            FileStream fs = null;
            VerificationDocument doc = null;
            try
            {
                fs = new FileStream(filename, FileMode.Open);
                doc = formatter.LoadDocument(fs);
            }
            finally
            {
                fs.Close();
            }
            return doc;
        }
    }
}
